<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCourses, updatePost } from '@/api/post.js'

const route = useRoute()
const router = useRouter()
const courseId = route.params.id

const form = ref({
  title: '',
  description: ''
})

// 获取课程详情
onMounted(async () => {
  try {
    const res = await getCourses()
    const course = res.data.courses.find(c => c.courseId == courseId)
    if (course) {
      form.value = {
        title: course.title,
        description: course.description || ''
      }
    }
  } catch (e) {
    console.error('获取课程详情失败:', e)
  }
})

// 提交修改
// 不能为空的课程标题，由前端来做基础的判断
const handleSubmit = async () => {
  if (!form.value.title) {
    alert('课程标题不能为空')
    return
  }
// 异常处理
  try {
    await updatePost(courseId, form.value)
    router.push('/backend/course')
  } catch (e) {
    console.error('修改失败:', e)
  }
}
</script>

<template>
    <div>
      <h1>修改课程</h1>
      <div class="card">
        <div style="max-width: 600px;">
          <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px;">课程标题：</label>
            <el-input v-model="form.title" />
          </div>

          <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px;">课程描述：</label>
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="5"
            />
          </div>

          <el-button type="primary" @click="handleSubmit">提交修改</el-button>
        </div>
      </div>
    </div>
</template>
